package com.gitee.hermer.engine.jars.starter.web.api;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.gitee.hermer.boot.jee.commons.encrypt.Md5Utils;
import com.gitee.hermer.boot.jee.commons.log.UtilsContext;
import com.gitee.hermer.boot.jee.commons.utils.FileUtils;
import com.gitee.hermer.boot.jee.commons.utils.JarUtils;
import com.gitee.hermer.boot.jee.commons.utils.StringUtils;
import com.gitee.hermer.engine.jars.core.context.IEngineAppContext;
import com.gitee.hermer.engine.jars.core.domain.BaseInfo;
import com.gitee.hermer.engine.jars.core.loader.EngineAppBeanScanner;
import com.gitee.hermer.engine.jars.core.loader.event.EngineAppInitializationEvent;

@RestController
@RequestMapping("execute-deploy")
public class EngineAppDeployController extends UtilsContext implements ApplicationEventPublisherAware{

	@Autowired
	private IEngineAppContext appContext;
	
	private ApplicationEventPublisher eventPublisher;
	
	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		this.eventPublisher = applicationEventPublisher;
	}


	@RequestMapping(value="file/ci-upload",method=RequestMethod.POST)
	@ResponseBody
	public BaseInfo<String> ciDeploy(@RequestParam("file") CommonsMultipartFile[] files,HttpServletRequest request){
		for(int i = 0;i<files.length;i++){  
			try{
				info("正在上传文件[%s]",files[i].getOriginalFilename());
				File temp = saveTempFile(files, i);
				EngineAppInitializationEvent event = EngineAppBeanScanner.createEngineInitializationEvent(temp);

				if(appContext.getCurrentLoaderState(event.getCacheKey()) != null){
					// stop now()
				}
				String md5 = StringUtils.toHexString(Md5Utils.md5(FileUtils.readBytes(temp)));
				
				String jarFileName = files[i].getOriginalFilename();
				
				File tempDir = JarUtils.createTempDirectory();
				info("正在解压至 -> [%s]",tempDir.getPath());
				JarUtils.unJar(temp, tempDir);
				File resources = FileUtils.file(tempDir, "resources");
				File deployFile = null;
				if(resources.exists()){
					deployFile = new File(FileUtils.getAbsolutePath("../../"));
					info("更新部署中 -> 替换静态资源文件 -> 替换地址[%s]",deployFile.getPath());
					FileUtils.copy(resources, deployFile, true);
				}
				File workJars = new File(FileUtils.getAbsolutePath("../work-jars"));
				deployFile = FileUtils.file(workJars, jarFileName+".md5");
				info("更新部署中 -> 替换模块MD5文件[%s] -> 内容-> [%s]",deployFile.getPath(),md5);
				FileUtils.write(deployFile.getPath(), md5);
				deployFile = FileUtils.file(workJars, jarFileName);
				info("更新部署中 -> 替换容器JAR文件 -> 替换地址[%s]",deployFile.getPath());
				FileUtils.copy(temp, deployFile, true);
				eventPublisher.publishEvent(EngineAppBeanScanner.createEngineInitializationEvent(deployFile));
			}catch (Exception e) {
				error(e.getMessage(),e);
				return new BaseInfo<String>("",false);
			}
		}
		return new BaseInfo<String>("","上传成功！");
	}

	private File saveTempFile(CommonsMultipartFile[] files, int i) throws IOException, FileNotFoundException {
		File temp = File.createTempFile(new Date().getTime()+"", ".jar");
		info("服务器存根地址 -> [%s]",temp.getPath());
		FileUtils.writeFromStream(files[i].getInputStream(), temp);
		return temp;
	}

	

}
